//
//  CreateOrderViewController.swift
//  Box
//
//  Created by mn on 2025/4/4.
//

import UIKit

class CreateOrderViewController: UIViewController, UIGestureRecognizerDelegate {
    
    private let orderView = GoodsOrderView()
    var goodsModel: GoodsModel?{
        didSet{
            orderView.goodsModel = goodsModel
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupView()
    }
    
    private func setupView() {
        view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissController))
        view.addGestureRecognizer(tapGesture)
                
        view.addSubview(orderView)
        orderView.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(393)
        }
        
        tapGesture.delegate = self
        orderView.buyButton.addAction {
            [weak self] in
            self?.buyGoods()
        }
    }
    
    func buyGoods()  {
        guard let goodsModel else { return }
        APIService.request(api: .buyGoods(goodsId: goodsModel.id,
                                          count: orderView.quantitySelectorView.count)) {
            [weak self] (result, response) in
            if result.success {
                self?.toast("购买成功，去仓库查看")
                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                    self?.dismiss(animated: false)
                }
            } else {
                self?.toast(result.message)
            }
        }
    }
    
    
    @objc private func dismissController() {
        dismiss(animated: false, completion: nil)
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        return !orderView.frame.contains(touch.location(in: view))
    }
}
